﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using CoreShop.App;
using CoreShop.Library;
using CoreShop.Services;
using System.Windows.Forms;
using CoreShop.Model;
using CoreShop.PrintService;
using SqlSugar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar;
using Yitter.IdGenerator;
using SqlSugar.Extensions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Sunny.UI;
using System.Xml;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using WebKit.DOM;
using static CoreShop.Library.GlobalEnumVars;
using System.Diagnostics.Metrics;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Cmp;
using System.ComponentModel;
using Org.BouncyCastle.Asn1.X9;
using System.Diagnostics;

namespace CoreShop.App
{
    public class ActivitieUtil
    {        
        /// <summary>
        /// 促销活动
        /// </summary>
        public struct ActivitieData
        {
            /// <summary>
            /// 限时特价
            /// </summary>
            public static bool SteepDescent { get; set; } = false;

            /// <summary>
            /// 限时折扣
            /// </summary>
            public static bool DiscountLimitedTime { get; set; } = false;

            /// <summary>
            /// 满减活动 
            /// </summary>
            public static bool SpendingEnough { get; set; } = false;

            /// <summary>
            /// 第二件半价
            /// </summary>
            public static bool TheNActivity { get; set; } = false;

            /// <summary>
            /// 第二件0元 
            /// </summary>
            public static bool TheSecondPieceZero { get; set; } = false;

            /// <summary>
            /// 满折活动 
            /// </summary>
            public static bool FoldingActivity { get; set; } = false;
        }

        /// <summary>
        /// 活动初始化
        /// </summary>
        public void ActivitieInit()
        {
            ActivitieData.SteepDescent = false;
            ActivitieData.DiscountLimitedTime = false;
            ActivitieData.SpendingEnough = false;
            ActivitieData.TheNActivity = false;
            ActivitieData.TheSecondPieceZero = false;
            ActivitieData.FoldingActivity = false;

            try
            {
                //1、活动类型-限时折扣
                var where1 = Expressionable.Create<activitymaster>();
                where1 = where1.And(p => p.status == (int)GlobalEnumVars.ActivityStatus.Valid);//审核状态
                where1 = where1.And(p => p.activityEndDate >= DateTime.Now);//有效期范围
                where1 = where1.And(p => p.activityTypeId == (int)GlobalEnumVars.ActivityEnum.特价);
                where1 = where1.And(p => p.activitySubTypeId == (int)GlobalEnumVars.ActivitySubType.限时折扣);
                ActivitieData.DiscountLimitedTime = new activitymasterServices().IsAny(where1.ToExpression());

                //2、活动类型-限时折扣
                var where2 = Expressionable.Create<activitymaster>();
                where2 = where2.And(p => p.status == (int)GlobalEnumVars.ActivityStatus.Valid);//审核状态
                where2 = where2.And(p => p.activityEndDate >= DateTime.Now);//有效期范围
                where2 = where2.And(p => p.activityTypeId == (int)GlobalEnumVars.ActivityEnum.特价);
                where2 = where2.And(p => p.activitySubTypeId == (int)GlobalEnumVars.ActivitySubType.限时特价);
                ActivitieData.SteepDescent = new activitymasterServices().IsAny(where2.ToExpression());

                //3、活动类型-满减
                var where3 = Expressionable.Create<activitymaster>();
                where3 = where3.And(p => p.status == (int)GlobalEnumVars.ActivityStatus.Valid);//审核状态                
                where3 = where3.And(p => p.activityEndDate >= DateTime.Now);//有效期范围
                where3 = where3.And(p => p.activityTypeId == (int)GlobalEnumVars.ActivityEnum.满减);
                ActivitieData.SpendingEnough = new activitymasterServices().IsAny(where3.ToExpression());

                //4、活动类型-第二件半价
                var where4 = Expressionable.Create<activitymaster>();
                where4 = where4.And(p => p.status == (int)GlobalEnumVars.ActivityStatus.Valid);//审核状态
                where4 = where4.And(p => p.activityEndDate >= DateTime.Now);//有效期范围
                where4 = where4.And(p => p.activityTypeId == (int)GlobalEnumVars.ActivityEnum.第N件商品);
                where4 = where4.And(p => p.activitySubTypeId == (int)GlobalEnumVars.ActivitySubType.第二件半价);
                ActivitieData.TheNActivity = new activitymasterServices().IsAny(where4.ToExpression());

                //5、活动类型-第二件0元
                var where5 = Expressionable.Create<activitymaster>();
                where5 = where5.And(p => p.status == (int)GlobalEnumVars.ActivityStatus.Valid);//审核状态
                where5 = where5.And(p => p.activityEndDate >= DateTime.Now);//有效期范围
                where5 = where5.And(p => p.activityTypeId == (int)GlobalEnumVars.ActivityEnum.第N件商品);
                where5 = where5.And(p => p.activitySubTypeId == (int)GlobalEnumVars.ActivitySubType.第二件0元);
                ActivitieData.TheSecondPieceZero = new activitymasterServices().IsAny(where5.ToExpression());

                //6、活动类型-满折活动
                var where6 = Expressionable.Create<activitymaster>();
                where6 = where6.And(p => p.status == (int)GlobalEnumVars.ActivityStatus.Valid);//审核状态
                where6 = where6.And(p => p.activityEndDate >= DateTime.Now);//有效期范围
                where6 = where6.And(p => p.activitySubTypeId == (int)GlobalEnumVars.ActivitySubType.满折活动);
                ActivitieData.FoldingActivity = new activitymasterServices().IsAny(where6.ToExpression());
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        /// 下载活动到本地
        /// </summary>
        /// <param name="exchange"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int GetActivityList(corecmsexchange exchange, ref string msg)
        {
            var count = new PosRemoteServices(AppConstVars.sUrl).GetActivityList(AppConstVars.sysStore, AppConstVars.sysUser, exchange, ref msg);
            if (count > 0) ActivitieInit();
            return count;
        }

        #region 促销计算(限时特价、限时折扣）
        /// <summary>
        /// 促销计算(限时特价、限时折扣）
        /// </summary>
        public bool SetOrderingPromotion(corecmsfoodordering ordering, corecmsuser member, ref string msgStr)
        {
            //限时特价与限时折扣促销计算
            if (SetOrderingDiscount(ordering, AppConstVars.sysUser.storeId, member, ref msgStr)) return true;

            //第二件半价与第二件0元计算
            //if (SetOrderingTheSecondPiece(ordering, memberId, ref msgStr)) return true;
            return true;
        }

        /// <summary>
        /// 促销计算(限时特价、限时折扣）
        /// </summary>
        public bool SetOrderingPromotionAll(List<corecmsfoodordering> orderingList, corecmsuser member, ref string msgStr)
        {
            foreach (var ordering in orderingList)
            {
                //限时特价与限时折扣促销计算
                if (SetOrderingDiscount(ordering, AppConstVars.sysUser.storeId, member, ref msgStr)) continue;

                //促销计算(第二件半价与第二件0元计算）
                new ActivitieUtil().SetOrderingTheSecondPiece(orderingList, ordering, member);
            }

            //第二件半价与第二件0元计算
            //if (SetOrderingTheSecondPiece(ordering, memberId, ref msgStr)) return true;
            return true;
        }

        #endregion


        #region 促销计算(限时特价、限时折扣）
        /// <summary>
        /// 促销计算(限时特价、限时折扣）
        /// </summary>
        public bool SetOrderingDiscount(corecmsfoodordering ordering, long storeId, corecmsuser member, ref string msgStr)
        {
            if (!ordering.disItem) return false;//不允许打折
            //限购数量
            if (ordering.limitBuyQty > 0)
            {
                var buyQty0 = GetOrderingyQty(ordering, ordering.id);
                if (buyQty0 + ordering.quantity > ordering.limitBuyQty)
                {
                    msgStr = "每单限购数量为{0}，已超过限购数量。";
                    msgStr = string.Format(msgStr, ordering.limitBuyQty.ToString("0.##"));
                    return false;
                }
            }

            if (!ActivitieData.DiscountLimitedTime && !ActivitieData.SteepDescent) return true;//没有促销活动

            var activity = new activitygoodsServices().SetOrderingDiscount(ordering, storeId, member);
            if (activity != null)
            {
                var master = activity.master;
                if (master.limitBuyType == (int)LimitBuyType.LimitedQty)
                {
                    var buyQty = GetOrderingyQty(ordering, ordering.id);
                    if (buyQty + ordering.quantity > master.limitBuyQty)
                    {
                        msgStr = "活动名称<{0}>每单限购数量为{1}，已超过限购数量。";
                        msgStr = string.Format(msgStr, master.activityInfoName, master.limitBuyQty.ToString("0.##"));
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 某商品的购物车合计
        /// </summary>
        /// <param name="ordering"></param>
        /// <returns></returns>
        public decimal GetOrderingyQty(corecmsfoodordering ordering, long excludeOrderId)
        {
            var foodorderingSrv = new corecmsfoodorderingServices();
            var where = Expressionable.Create<corecmsfoodordering>();
            where = where.And(p => p.orderId == ordering.orderId);
            where = where.And(p => p.id != excludeOrderId);
            where = where.And(p => p.foodId == ordering.foodId && p.foodSpecId == ordering.foodSpecId);
            var buyQty = foodorderingSrv.AsQueryable().Where(where.ToExpression()).Sum(p => p.quantity);
            return buyQty;
        }
        #endregion

        #region 满减活动计算
        /// <summary>
        /// 满减活动计算
        /// </summary>
        public decimal GetSpendingEnough(corecmsfoodorderingmaster master, corecmsuser member)
        {
            if (!ActivitieData.SpendingEnough) return 0;//没有促销活动

            decimal freeAmount = 0;//扣减的金额
            var where = Expressionable.Create<corecmsfoodordering>();
            where = where.And(p => p.orderId == master.orderId && p.dataType == (int)GlobalEnumVars.OrderingDataType.Normal);
            var orderings = new corecmsfoodorderingServices().AsQueryable().Where(where.ToExpression()).ToList();
            if ((orderings == null) || (orderings.Count == 0)) return 0;

            //购物车对应的商品分类对象
            var orderingTypes = new corecmsfoodcategoryServices().GetOrderingGoodsTypes(orderings);

            decimal dOrderingAmt = orderings.Sum(p => p.realAmount) ;//金额

            var activityList = new activitymasterServices().GetSpendingEnoughList(master, orderings, member, orderingTypes);
            if ((activityList == null) || (activityList.Count == 0)) return 0;
            var actIds = activityList.Select(p => p.activityInfoId).Distinct().ToList();

            var whereResp = Expressionable.Create<activitylineresp>();
            whereResp = whereResp.And(p => actIds.Contains(p.activityInfoId) && p.condition1 <= dOrderingAmt && p.activitySubTypeId == (int)GlobalEnumVars.ActivitySubType.满减活动);            
            var activitylineresps = new activitylinerespServices().AsQueryable().Where(whereResp.ToExpression()).ToList();

            var sortActIds = actIds.OrderByDescending(n => n).ToList(); // 得到降序排列的新列表
            //判断是否满足条件
            foreach (var actId in sortActIds)
            {
                //activitymaster数据
                var activityBill = activityList.Where(p=>p.activityInfoId == actId).ToList();
                if (activityBill == null || activityBill.Count == 0) continue;
                var activityItem = activityBill.First();

                GetSpendingEnoughExclude(activityItem, orderings, orderingTypes);//计算排除

                //参与促销的订单商品的金额
                decimal activityAmt = activityBill.Sum(p => p.realAmount) - activityItem.excAmount;

                //查找优惠层级
                var lineresp = activitylineresps.Where(p => p.activityInfoId == actId 
                    && (p.condition1 <= activityAmt && p.activitySubTypeId == (int)GlobalEnumVars.ActivitySubType.满减活动))
                    .OrderByDescending(p=>p.condition2).ToList();
                if (lineresp.Count > 0)
                {
                    var linerespRow = lineresp.First();
                    freeAmount = CommFunc.ConvertToDecimal(linerespRow.condition2);
                    return CommFunc.GetSumAmount(freeAmount, (int)GlobalEnumVars.AmountDecimal.FloorPoint2);//只保留两位   
                }             
            }
            return 0;
        }

        /// <summary>
        /// 得到排除的金额
        /// </summary>
        /// <returns></returns>
        public void GetSpendingEnoughExclude(ActivityOrderingDto activity, List<corecmsfoodordering> orderings, List<OrderingGoodsTypeDto> orderingTypes)
        {
            //指定商品，无排除
            if (activity.goodsType == (int)GlobalEnumVars.ActivityGoodsType.Goods) return;

            var goodsIds = orderings.Select(p => p.foodId).Distinct().ToList();
            var whereGoods = Expressionable.Create<activitygoodsexclude>();
            whereGoods = whereGoods.And(p => p.activityInfoId == activity.activityInfoId && goodsIds.Contains(p.spuId));
            //排除商品
            var excGoodsIds = new activitygoodsexcludeServices().AsQueryable().Where(whereGoods.ToExpression()).Select(p => p.spuId).Distinct().ToList();
            if (excGoodsIds.Count > 0)
            {
                activity.excAmount = orderings.Where(p => excGoodsIds.Contains(p.foodId)).Sum(p => p.realAmount);
                return;
            }

            //排除分类
            List<long> orderingTypeIds = orderingTypes.Select(p => p.foodTypeId).Distinct().ToList();
            var whereTypes = Expressionable.Create<activitysort>();
            whereTypes = whereTypes.And(p => p.activityInfoId == activity.activityInfoId);
            whereTypes = whereTypes.And(p => orderingTypeIds.Contains(p.itemSortId));
            //whereTypes = whereTypes.And(p => p.excludeFLag == true);
            var sortList = new activitysortServices().AsQueryable().Where(whereTypes.ToExpression()).ToList();
            var excSortIds = sortList.Where(p => p.excludeFLag == true).Select(p => p.itemSortId).Distinct().ToList();
            if (excSortIds.Count > 0)
            {
                var excOrderingIds = orderingTypes.Where(p => excSortIds.Contains(p.foodTypeId)).Select(p => p.orderingId).Distinct().ToList();
                activity.excAmount = orderings.Where(p => excOrderingIds.Contains(p.id)).Sum(p => p.realAmount);                
            }

            //只统计指定分类的金额
            if (activity.goodsType == (int)GlobalEnumVars.ActivityGoodsType.Type)
            {
                var sortIds = sortList.Where(p => p.excludeFLag == false).Select(p => p.itemSortId).Distinct().ToList();
                if (sortIds.Count > 0)
                {
                    var orderingIds = orderingTypes.Where(p => sortIds.Contains(p.foodTypeId)).Select(p => p.orderingId).Distinct().ToList();
                    activity.realAmount = orderings.Where(p => orderingIds.Contains(p.id)).Sum(p => p.realAmount);                    
                }
            }
            return;
        }


        #endregion

        #region 满折活动计算
        /// <summary>
        /// 满减活动计算
        /// </summary>
        public decimal GetFoldingActivity(corecmsfoodorderingmaster master, corecmsuser member)
        {
            if (!ActivitieData.FoldingActivity) return 0;//没有促销活动

            decimal freeAmount = 0;//扣减的金额
            var where = Expressionable.Create<corecmsfoodordering>();
            where = where.And(p => p.orderId == master.orderId && p.dataType == (int)GlobalEnumVars.OrderingDataType.Normal);
            var orderings = new corecmsfoodorderingServices().AsQueryable().Where(where.ToExpression()).ToList();
            if ((orderings == null) || (orderings.Count == 0)) return 0;

            //购物车对应的商品分类对象
            var orderingTypes = new corecmsfoodcategoryServices().GetOrderingGoodsTypes(orderings);

            decimal dOrderingQty = orderings.Sum(p => p.quantity);//数量

            var activityList = new activitymasterServices().GetFoldingActivityList(master, orderings, member, orderingTypes);
            if ((activityList == null) || (activityList.Count == 0)) return 0;
            var actIds = activityList.Select(p => p.activityInfoId).Distinct().ToList();

            var whereResp = Expressionable.Create<activitylineresp>();
            whereResp = whereResp.And(p => actIds.Contains(p.activityInfoId) && p.condition1 <= dOrderingQty && p.activitySubTypeId == (int)GlobalEnumVars.ActivitySubType.满折活动);            
            var activitylineresps = new activitylinerespServices().AsQueryable().Where(whereResp.ToExpression()).ToList();

            var sortActIds = actIds.OrderByDescending(n => n).ToList(); // 得到降序排列的新列表
            //判断是否满足条件
            foreach (var actId in sortActIds)
            {
                //activitymaster数据
                var activityBill = activityList.Where(p => p.activityInfoId == actId).ToList();
                if (activityBill == null || activityBill.Count == 0) continue;
                var activityItem = activityBill.First();

                GetFoldingActivityExclude(activityItem, orderings, orderingTypes);//计算排除

                //参与促销的订单商品的数量
                decimal activityQty = activityBill.Sum(p => p.quantity) - activityItem.excQuantity;

                //查找优惠层级
                var lineresp = activitylineresps.Where(p => p.activityInfoId == actId
                    && (p.condition1 <= activityQty && p.activitySubTypeId == (int)GlobalEnumVars.ActivitySubType.满折活动))
                    .OrderByDescending(p => p.condition2).ToList();
                if (lineresp.Count > 0)
                {
                    //decimal dCanDismountAmt = orderings.Sum(p => p.realAmount) - activityItem.excAmount;//可打折金额
                    decimal dCanDismountAmt = activityItem.realAmount - activityItem.excAmount;//可打折金额
                    var linerespRow = lineresp.First();
                    freeAmount = dCanDismountAmt - dCanDismountAmt * CommFunc.ConvertToDecimal(linerespRow.condition2) / 10;
                    return CommFunc.GetSumAmount(freeAmount, (int)GlobalEnumVars.AmountDecimal.FloorPoint2);//只保留两位
                }
            }

            return 0;
        }

        /// <summary>
        /// 得到排除的金额
        /// </summary>
        /// <returns></returns>
        public void GetFoldingActivityExclude(ActivityOrderingDto activity, List<corecmsfoodordering> orderings, List<OrderingGoodsTypeDto> orderingTypes)
        {
            //指定商品，无排除
            if (activity.goodsType == (int)GlobalEnumVars.ActivityGoodsType.Goods) return;

            var goodsIds = orderings.Select(p => p.foodId).Distinct().ToList();
            var whereGoods = Expressionable.Create<activitygoodsexclude>();
            whereGoods = whereGoods.And(p => p.activityInfoId == activity.activityInfoId && goodsIds.Contains(p.spuId));
                        
            //排除商品
            var excGoodsIds = new activitygoodsexcludeServices().AsQueryable().Where(whereGoods.ToExpression()).Select(p => p.spuId).Distinct().ToList();
            if (excGoodsIds.Count > 0)
            {
                activity.excAmount = orderings.Where(p => excGoodsIds.Contains(p.foodId)).Sum(p => p.realAmount);
                activity.excQuantity = orderings.Where(p => excGoodsIds.Contains(p.foodId)).Sum(p => p.quantity);
                return;
            }

            //排除分类
            List<long> orderingTypeIds = orderingTypes.Select(p => p.foodTypeId).Distinct().ToList();
            var whereTypes = Expressionable.Create<activitysort>();
            whereTypes = whereTypes.And(p => p.activityInfoId == activity.activityInfoId);
            whereTypes = whereTypes.And(p => orderingTypeIds.Contains(p.itemSortId));
            //whereTypes = whereTypes.And(p => p.excludeFLag == true);
            var sortList = new activitysortServices().AsQueryable().Where(whereTypes.ToExpression()).ToList();
            var excSortIds = sortList.Where(p=>p.excludeFLag == true).Select(p => p.itemSortId).Distinct().ToList();
            if (excSortIds.Count > 0)
            {
                var excOrderingIds = orderingTypes.Where(p => excSortIds.Contains(p.foodTypeId)).Select(p => p.orderingId).Distinct().ToList();
                activity.excAmount = orderings.Where(p => excOrderingIds.Contains(p.id)).Sum(p => p.realAmount);
                activity.excQuantity = orderings.Where(p => excOrderingIds.Contains(p.id)).Sum(p => p.quantity);
            }

            //只统计指定分类的金额和数量
            if (activity.goodsType == (int)GlobalEnumVars.ActivityGoodsType.Type)
            {
                var sortIds = sortList.Where(p => p.excludeFLag == false).Select(p => p.itemSortId).Distinct().ToList();
                if (sortIds.Count > 0)
                {
                    var orderingIds = orderingTypes.Where(p => sortIds.Contains(p.foodTypeId)).Select(p => p.orderingId).Distinct().ToList();
                    activity.realAmount = orderings.Where(p => orderingIds.Contains(p.id)).Sum(p => p.realAmount);
                    activity.quantity = orderings.Where(p => orderingIds.Contains(p.id)).Sum(p => p.quantity);
                }
            }

            return;
        }

        #endregion

        #region 第二件半价与第二件0元计算
        /// <summary>
        /// 促销计算(第二件半价与第二件0元计算）
        /// </summary>
        public bool SetOrderingTheSecondPiece(List<corecmsfoodordering> orderingDetail,corecmsfoodordering orderingSelected, corecmsuser member)
        {
            //没有促销活动
            if (!ActivitieData.TheNActivity && !ActivitieData.TheSecondPieceZero) return false;

            //称重商品不执行这个促销
            if (orderingSelected.weighType.ObjToInt() == (int)GlobalEnumVars.WeighType.Weigh) return false;

            //只有正常商品才能计算促销
            if (orderingSelected.dataType != (int)GlobalEnumVars.OrderingDataType.Normal) return false;

            //数量小于2，不执行促销
            var buyQty = orderingDetail.Where(p=>p.foodSpecId == orderingSelected.foodSpecId && p.id != orderingSelected.id).Sum(p=>p.quantity);
            if (buyQty + orderingSelected.quantity < 2) return false;

            //p.sourceId == ordering.id说明该行已有促销
            var orderingChild = orderingDetail.Where(p => p.sourceId == orderingSelected.id).ToList();
            if (orderingChild.Any()) return false;            

            var activity = new activitygoodsServices().SetOrderingTheSecondPiece(orderingSelected, member);
            if (activity == null) return false;

            var orderingSrv = new corecmsfoodorderingServices();

            if (orderingSelected.quantity > 1)
            {
                //2.2、新增一行赠送记录
                var newDetails = new List<corecmsfoodordering>();                
                int rowId = orderingSrv.AsQueryable().Where(p => p.id == orderingSelected.id).Max(p => p.rowId) + 1;
                string strNewItem = JsonConvert.SerializeObject(orderingSelected);
                var newOrdering = JsonConvert.DeserializeObject<corecmsfoodordering>(strNewItem);
                decimal sourceQty = orderingSelected.quantity - 1;

                //对原来的记录进行修改
                orderingSelected.quantity = sourceQty;
                orderingSelected.amount = orderingSelected.price * sourceQty;
                orderingSelected.sourcePrice = orderingSelected.realPrice;
                orderingSelected.realAmount = orderingSelected.realPrice * sourceQty;
                orderingSelected.allAmount = orderingSelected.realAmount + orderingSelected.taskAmount + orderingSelected.feedAmount;

                //对原来的记录进行修改
                newOrdering.id = 0;
                newOrdering.rowId = rowId;
                newOrdering.sourceId = orderingSelected.id;
                newOrdering.quantity = sourceQty;
                if (activity.master.activitySubTypeId == (int)GlobalEnumVars.ActivitySubType.第二件半价)
                {
                    newOrdering.dataType = (int)GlobalEnumVars.OrderingDataType.ActivityGift;
                }                    
                else
                    newOrdering.dataType = (int)GlobalEnumVars.OrderingDataType.Present;
                newOrdering.amount = orderingSelected.price;
                newOrdering.sourcePrice = orderingSelected.realPrice;
                newOrdering.realPrice = orderingSelected.price * activity.master.discountRate;
                newOrdering.realAmount = orderingSelected.price * activity.master.discountRate;
                newOrdering.discount = activity.master.discountRate;
                newOrdering.taskAmount = 0;
                newOrdering.feedAmount = 0;
                newOrdering.allAmount = orderingSelected.price * activity.master.discountRate;
                newOrdering.createTime = DateTime.Now;

                newDetails.Add(newOrdering);
                newDetails.Add(orderingSelected);
                var bl = orderingSrv.InsertOrUpdate(newDetails);//保存明细
                return bl;
            }       
            else if (orderingSelected.quantity == 1)
            {
                //查询一条适合作为第一件商品促销
                var orderingChilds = orderingDetail.Where(p=>p.foodSpecId ==  orderingSelected.foodSpecId && p.dataType == (int)GlobalEnumVars.OrderingDataType.Normal).ToList();
                foreach (var child in  orderingChilds)
                {
                    var orderingChild0 = orderingDetail.Find(p => p.sourceId == child.id);//未绑定第二件商品
                    if (orderingChild0 == null)
                    {
                        orderingSelected.sourceId = child.id;
                        if (activity.master.activitySubTypeId == (int)GlobalEnumVars.ActivitySubType.第二件半价)
                        {
                            orderingSelected.dataType = (int)GlobalEnumVars.OrderingDataType.ActivityGift;
                        }
                        else
                            orderingSelected.dataType = (int)GlobalEnumVars.OrderingDataType.Present;
                        orderingSelected.sourcePrice = orderingSelected.realPrice;
                        orderingSelected.realPrice = orderingSelected.price * activity.master.discountRate;
                        orderingSelected.realAmount = orderingSelected.price * orderingSelected.quantity * activity.master.discountRate ;
                        orderingSelected.discount = activity.master.discountRate;
                        orderingSelected.allAmount = orderingSelected.realAmount + orderingSelected.taskAmount + orderingSelected.feedAmount;
                        var bl = orderingSrv.InsertOrUpdate(orderingSelected);//保存明细
                        return bl;
                    }                        
                }
            }
            return true;
        }
                
        #endregion
    }

}
